import time
import uuid

from tornado_request_mapping import request_mapping

from base_web import HttpBasicHandler
from common.user_constant import UserConstant
from services.sql_service.user_service import UserService

# 生成并保存用户的登录状态
active_sessions = {}


@request_mapping('/user')
class USerManageHandler(HttpBasicHandler):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user_service = UserService()

    @request_mapping('/get_params', 'get', '获取用户登录参数(用户等级下拉列表)')
    async def get_params(self):
        data = {
            'level_list': UserConstant.user_level
        }
        return self.send_response_data('success', data, '')

    @request_mapping('/get_all_user', 'get', '获取全部用户信息')
    async def get_all_user(self):
        resp = await self.user_service.get_all_user()
        return self.send_response_data(resp.code, resp.data, resp.msg)

    @request_mapping('/login_check', 'post', '验证登录')
    async def login_check(self):
        data = self.data
        resp = await self.user_service.login_check(data)
        if resp.code == 'success':
            user_id = resp.data['id']
            session_id = str(uuid.uuid4())
            active_sessions[session_id] = user_id
            # 设置Cookie的过期时间为一周
            self.set_cookie("session_id", session_id, expires_days=7)
            # self.set_cookie("session_id", session_id, expires=time.time() + 10)
        return self.send_response_data(resp.code, resp.data, resp.msg)

    @request_mapping('/logout', 'post', '登出')
    async def logout(self):
        session_id = self.get_cookie("session_id")
        # if not session_id:
        #     return self.send_response_data('success', '', '请先登录')
        if session_id in active_sessions:
            del active_sessions[session_id]
            self.clear_cookie("session_id")
        return self.send_response_data('success', '', '登出成功')

    @request_mapping('/change_pwd', 'post', '修改密码')
    async def change_pwd(self):
        data = self.data
        resp = await self.user_service.change_pwd(data)
        session_id = self.get_cookie("session_id")
        if session_id in active_sessions:
            del active_sessions[session_id]
            self.clear_cookie("session_id")
        return self.send_response_data(resp.code, resp.data, resp.msg)
